package org.giovanolli.mumi.view.converter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.component.UISelectItem;
import javax.faces.component.UISelectItems;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;

/**
 * The Class SelectItemsBaseConverter.
 */
public abstract class SelectItemsBaseConverter<T> implements Converter {

	public List<SelectItem> createSelectItems(UIComponent component) {
		List<SelectItem> items = new ArrayList<SelectItem>();
		Iterator<UIComponent> children = component.getChildren().iterator();

		while (children.hasNext()) {
			UIComponent child = children.next();

			if (child instanceof UISelectItem) {
				UISelectItem selectItem = (UISelectItem) child;

				items.add(new SelectItem(selectItem.getItemValue(), selectItem.getItemLabel()));
			} else if (child instanceof UISelectItems) {
				Object selectItems = ((UISelectItems) child).getValue();
				List<T> objectList = (List<T>) selectItems;
				if (objectList != null) {
					for (T object : objectList) {
						items.add(new SelectItem(getItemValue(object), getItemLabel(object)));
					}
				}
			}
		}

		return items;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext , javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		Object obj = SelectItemsUtils.findValueByStringConversion(context, component, createSelectItems(component).iterator(), value, this);
		return obj;

	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		String str = null;
		if (value != null) {
			str = getAsString(value);
		}
		return str;
	}

	public abstract String getAsString(Object value);

	public abstract String getItemLabel(T object);

	public abstract Object getItemValue(T object);
}